# -*- coding: utf-8 -*-
import os
import time
import threading
import setproctitle
from datetime import datetime

# 本地存储地址
loudao_dir="/home/ubuntu/workspace/kuake/data/kuake/tplink/loudao"
yangtai_chewei_dir="/home/ubuntu/workspace/kuake/data/kuake/tplink/yangtai"
# loudao_dir="/tmp/tplink/楼道/"
# yangtai_chewei_dir="/tmp/tplink/阳台车位/"

# rtsp 码流地址
loudao_rtsp="rtsp://admin:1234hjkl@192.168.31.91:554/stream1"
yangtai_chewei_rtsp="rtsp://admin:1234hjkl@192.168.31.194:554/stream1&channel=1"


# 楼道摄像头拉流线程
def loudao_thread_function():
    while True:
        now = datetime.now()
        print("Thread loudao is running, now: ", now)
        num_hour        = now.strftime("%H")
        num_min         = now.strftime("%M")
        if (int(num_hour) == 1) and (int(num_min) >= 0) and (int(num_min) <= 6):
            print("Thread loudao_thread_function now exit ")
            break
        now_hour_str    = now.strftime("%Y-%m/%d/%H/")
        now_hour        = os.path.join(loudao_dir, now_hour_str)
        base_min_second = now.strftime("%Mmin.mp4")
        now_min_second  = os.path.join(now_hour, base_min_second)

        print("now_hour:", now_hour)
        print("now_min_second:", now_min_second)
        os.system("mkdir -p " + now_hour)
        os.system("ffmpeg -i rtsp://admin:1234hjkl@192.168.31.91:554/stream1 -t 300 -c:v copy -c:a aac " + now_min_second)

# 阳台摄像头拉流线程
def yangtaichewei_thread_function():
    while True:
        now = datetime.now()
        print("Thread yangtaichewei is running, now: ", now)
        num_hour        = now.strftime("%H")
        num_min         = now.strftime("%M")
        if (int(num_hour) == 1) and (int(num_min) >= 0) and (int(num_min) <= 6):
            print("Thread yangtaichewei now exit ")
            break
        now_hour_str    = now.strftime("%Y-%m/%d/%H/")
        now_hour        = os.path.join(yangtai_chewei_dir, now_hour_str)
        base_min_second = now.strftime("%Mmin.mp4")
        now_min_second  = os.path.join(now_hour, base_min_second)

        print("now_hour:", now_hour)
        print("now_min_second:", now_min_second)
        os.system("mkdir -p " + now_hour)
        os.system("ffmpeg -i rtsp://admin:1234hjkl@192.168.31.194:554/stream1 -t 300 -c:v copy -c:a aac " + now_min_second)

if __name__ == "__main__":
    setproctitle.setproctitle("tplink_rtsp")
    thread_loudao = threading.Thread(target=loudao_thread_function)
    thread_loudao.start()
    yangtaichewei_thread = threading.Thread(target=yangtaichewei_thread_function)
    yangtaichewei_thread.start()

    # 这些线程为了稳定性,每天凌晨 1:00 -- 1:06 之间重启
    print("main thread start ok 1..")
    thread_loudao.join()
    print("main thread start ok 2..")
    yangtaichewei_thread.join()
    print("main thread start ok 3..")
    time.sleep(300)
